package cs419.magnusmi.trackitcs;

import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Mikael Magnuson on 2/6/14.
 */

public class History extends ActionBarActivity {
    ListView listView;
    Button returnB;
    ItemGetList iGetList;
    Context k;
    String user;
    String API;
    TextView title;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);

        //define listview for inventory
        listView = (ListView) findViewById(R.id.listView);

        //capture context of activity for use in asynchronous activity
        k = this;

        Intent i = getIntent();
        user = i.getStringExtra("user");
        API = i.getStringExtra("API");
        String ID = i.getStringExtra("id");

        title = (TextView) findViewById(R.id.historyLabel);
        title.setText("Checkout history for Item: " + ID);

        //create new async array list to hold item information and execute get task
        iGetList = new ItemGetList();
        iGetList.execute(ID);


        //attach add button
        returnB = (Button) findViewById(R.id.RetButton);

        returnB.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                //Launching add activity
                Intent i = new Intent(getApplicationContext(), Inventory.class);
                Utility.addToIntent(i, user, API);
                startActivity(i);
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu (Menu menu)  {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.logout:
                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                //clear stack to enforce logout (http://stackoverflow.com/questions/3007998/on-logout-clear-activity-history-stack-preventing-back-button-from-opening-l)
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                        Intent.FLAG_ACTIVITY_CLEAR_TASK |
                        Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
                return true;
            case R.id.inventory_menu:
                Intent j = new Intent(getApplicationContext(), Inventory.class);
                Utility.addToIntent(j, user, API);
                startActivity(j);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to get item list
     * the user.
     */

    public class ItemGetList extends AsyncTask<String, Void, JSONObject> {

        //array list to store item descriptor strings
        ArrayList<String> logs  = new ArrayList<String>();

        /**
         * Gets inventory from database
         * @param params none
         * @return json object containing database inventory results
         */
        @Override
        protected JSONObject doInBackground(String... params) {

            //DEBUG System.out.println("Inventory started");

            //url of PHP to get list
            String getList = "http://web.engr.oregonstate.edu/~cohenad/cs419/index.php/History";

            String id = params[0];

            //execute get request for list
            JSONParser jsonParser = new JSONParser();
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("id", id));

            JSONObject json = jsonParser.makeHttpRequest(getList, "GET", parameters);
            //DEBUG out.println("Inventory done");
            return json;
        }

        /**
         * Method to add content to listview after getting content online
         * @param json json array containing results of HTTP get
         */
        @Override
        protected void onPostExecute(JSONObject json) {


            //parse JSON array
            try{
                //create list of items to print.  these are saved in json array with identifier "display[index]"
                int length = json.getInt("length");
                for (int i = 0; i < length; i++){
                    logs.add(json.getString("display" + i));
                }
            }
            catch (JSONException e) {
                Log.d("JSONErr", "JSON error");
            }

            // Define a new Adapter
            // First parameter - Context
            // Second parameter - Layout for the row
            // Third parameter - ID of the TextView to which the data is written
            // Fourth - the Array of data (returned from async task)
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(k,
                    android.R.layout.simple_list_item_1, android.R.id.text1, logs){
                @Override
                public View getView(int position, View convertView,
                                    ViewGroup parent) {
                    View view =super.getView(position, convertView, parent);

                    TextView textView=(TextView) view.findViewById(android.R.id.text1);

                    /*YOUR CHOICE OF COLOR*/
                    textView.setTextColor(Color.WHITE);

                    return view;
                }

            };

            // Assign adapter to ListView
            listView.setAdapter(adapter);

        }
    }
}
